import Vue from 'vue'
import VueRouter from 'vue-router'
import storage from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('../views/test.vue'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue'),
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/register.vue'),
  },
  // front
  {
    path: '/front',
    component: () => import('../views/front'),
    children: [
      {
        path: 'home',
        component: () => import('../views/front/home'),
      },
      {
        path: 'profile',
        component: () => import('../views/front/profile'),
      },
      {
        path: 'cart',
        component: () => import('../views/front/cart'),
      },
      {
        path: 'order',
        component: () => import('../views/front/order'),
      },
    ],
  },
  // back
  {
    path: '/back',
    component: () => import('@/views/back'),
    children: [
      {
        path: 'users',
        component: () => import('@/views/back/users'),
      },
      {
        path: 'products',
        component: () => import('@/views/back/products'),
      },
      {
        path: 'orders',
        component: () => import('@/views/back/orders'),
      },
    ],
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 重复路由
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

router.beforeEach((to, from, next) => {
  const token = storage.getToken()
  if (
    to.name !== 'login' &&
    !token &&
    to.name !== 'register' &&
    to.name !== 'test'
  ) {
    next({ name: 'login' })
  } else {
    next()
  }
})
export default router
